<template>
  <el-space
    size="large"
    direction="vertical"
    style="width: 100%"
    alignment="flex-start"
    fill
  >
    <!-- 项目简介 -->
    <div v-if="detailData?.acceptApplyRespVO" class="project-title">
      <div class="item">
        <span class="label">项目验收申请ID：</span>
        <span>{{ detailData.acceptApplyRespVO.id }}</span>
      </div>
      <div class="item">
        <span class="label">审核状态：</span>
        <span>
          {{
            dictStore.getDictLabelForValue(
              'audit_status',
              detailData.acceptApplyRespVO.status
            )
          }}
        </span>
      </div>
      <div class="item">
        <span class="label">记录创建人：</span>
        <span>{{ detailData.acceptApplyRespVO.creatorName }}</span>
      </div>
      <div class="item">
        <span class="label">记录创建时间：</span>
        <span>
          {{
            $XEUtils.toDateString(
              detailData.acceptApplyRespVO.createTime,
              'yyyy-MM-dd HH:mm:ss'
            )
          }}
        </span>
      </div>
    </div>
    <!-- 项目简介 -->
    <!-- 项目信息 -->
    <div v-if="detailData.projectInfo" class="box" style="width: 100%">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon2.png" alt="" class="icon" />
          <span>项目信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData.projectInfo]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="projectCode" title="项目编号" />
          <vxe-column field="projectName" title="项目名称" />
          <vxe-column field="projectLevel" title="项目级别">
            <template #default="{ row }">
              {{
                dictStore.getDictLabelForValue(
                  'project_level',
                  row.projectLevel
                )
              }}
            </template>
          </vxe-column>
          <vxe-column field="projectTypeName" title="项目类型" />
          <vxe-column field="keyProject" title="是否重点项目">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('yes_no', row.keyProject) }}
            </template>
          </vxe-column>
          <vxe-column field="headerName" title="项目负责人" />
        </vxe-table>
      </el-space>
    </div>
    <!-- 项目信息 -->
    <!-- 课题信息 -->
    <div v-if="detailData.topicInfo" class="box">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon2.png" alt="" class="icon" />
          <span>课题信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData.topicInfo]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="id" title="课题编号" />
          <vxe-column field="name" title="课程名称" />
          <vxe-column field="leader" title="课题负责人" />
          <vxe-column field="type" title="课题类型">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('topic_type', row.type) }}
            </template>
          </vxe-column>
          <vxe-column field="subjectAreaText" title="专业领域" />
          <vxe-column
            field="researchStartDate"
            title="研究开始时间"
            :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
          />
          <vxe-column
            field="researchEndDate"
            title="研究结束时间"
            :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
          />
          <vxe-column field="estimatedBudget" title="预计投入经费（万元）" />
          <vxe-column field="externalCooperationRequired" title="是否需要外协">
            <template #default="{ row }">
              {{
                dictStore.getDictLabelForValue(
                  'yes_no',
                  row.externalCooperationRequired
                )
              }}
            </template>
          </vxe-column>
          <vxe-column field="leadingUnitName" title="承担单位" />
          <vxe-column field="collaboratingUnitNames" title="协作单位" />
        </vxe-table>
      </el-space>
    </div>
    <!-- 课题信息 -->
    <!-- 其他信息 -->
    <div v-if="detailData.acceptApplyRespVO" class="box">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon4.png" alt="" class="icon" />
          <span>其他信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData.acceptApplyRespVO]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="type" title="验收类型">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('accept_type', row.status) }}
            </template>
          </vxe-column>
        </vxe-table>
      </el-space>
    </div>
    <!-- 其他信息 -->
  </el-space>

  <el-form
    ref="ruleFormRef"
    style="max-width: 800px; margin-top: 40px"
    :model="ruleForm"
    :rules="rules"
  >
    <template v-if="detailData.acceptApplyRespVO?.type == 1">
      <el-form-item label="验收结论:" prop="conclusion">
        <el-select
          v-model="ruleForm.conclusion"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('accept_conclusion')"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="验收时间:" prop="conclusionDate">
        <el-date-picker
          v-model="ruleForm.conclusionDate"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="flex: 0 0 400px"
        />
      </el-form-item>
      <el-form-item label="验收地点:" prop="conclusionAddress">
        <el-input v-model="ruleForm.conclusionAddress" />
      </el-form-item>
      <el-form-item label="验收井号:" prop="wellNum">
        <el-select
          v-model="ruleForm.wellNum"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('well_no')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配合井队及所属单位:" prop="wellTeam">
        <el-select
          v-model="ruleForm.wellTeam"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in depts"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预期验收指标:" prop="preAcceptIndicator">
        <el-input v-model="ruleForm.preAcceptIndicator" type="textarea" />
      </el-form-item>
    </template>
    <template v-else-if="detailData.acceptApplyRespVO?.type == 2">
      <el-form-item label="验收结论:" prop="conclusion">
        <el-select
          v-model="ruleForm.conclusion"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('accept_conclusion')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="外协单位:" prop="outUnitName">
        <el-input v-model="ruleForm.outUnitName" />
      </el-form-item>
      <el-form-item label="外协负责人:" prop="outUnitLeaderName">
        <el-input v-model="ruleForm.outUnitLeaderName" />
      </el-form-item>
      <el-form-item label="合同履行周期:" prop="contractFulfill">
        <el-date-picker
          v-model="ruleForm.contractFulfill"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="flex: 0 0 400px"
        />
      </el-form-item>
      <el-form-item label="预计验收时间:" prop="conclusionDate">
        <el-date-picker
          v-model="ruleForm.conclusionDate"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="flex: 0 0 400px"
        />
      </el-form-item>
      <el-form-item label="预计验收方式:" prop="conclusionWay">
        <el-select
          v-model="ruleForm.conclusionWay"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('conclusion_way')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否通过本单位自验收:" prop="seftAccept">
        <el-select
          v-model="ruleForm.seftAccept"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('yes_no')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同主要服务内容:" prop="contractContent">
        <el-input v-model="ruleForm.contractContent" type="textarea" />
      </el-form-item>
      <el-form-item label="预期验收指标:" prop="preAcceptIndicator">
        <el-input v-model="ruleForm.preAcceptIndicator" type="textarea" />
      </el-form-item>
    </template>
  </el-form>

  <commonFooterBar>
    <el-button :loading="loading" @click="submitForm(ruleFormRef)">
      保存为草稿
    </el-button>
    <el-button
      type="primary"
      :loading="loading"
      @click="submitForm(ruleFormRef, 2)"
    >
      确认提交
    </el-button>
  </commonFooterBar>
</template>

<script setup>
  import { useDictStore } from '@/store/modules/dict'
  import commonFooterBar from '@/components/commonFooterBar.vue'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { getDeptPage } from '@/api/system/dept/index'
  import {
    acceptApplyGet,
    acceptApplyUpdate,
  } from '@/api/project/accept/task-in'

  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const { closeTabNavigate } = useCloseTabNavigate()

  const $baseMessage = inject('$baseMessage')
  const $XEUtils = inject('$XEUtils')
  const dictStore = useDictStore()
  const route = useRoute()

  const detailData = ref({})

  const loading = ref(false)
  const ruleFormRef = ref()
  const ruleForm = reactive({
    conclusion: '',
    conclusionDate: [],
    conclusionAddress: '',
    wellNum: '',
    wellTeam: '',
    preAcceptIndicator: '',
    outUnitName: '',
    outUnitLeaderName: '',
    contractFulfill: [],
    conclusionWay: '',
    seftAccept: '',
    contractContent: '',
  })
  const rules = reactive({
    conclusion: [
      {
        required: true,
        message: '请选择验收结论',
        trigger: 'blur',
      },
    ],
    conclusionDate: [
      {
        required: true,
        message: '请选择验收时间',
        trigger: 'change',
      },
    ],
    contractFulfill: [
      {
        required: true,
        message: '请选择合同履行周期',
        trigger: 'change',
      },
    ],
    conclusionAddress: [
      {
        required: true,
        message: '请输入验收地点',
        trigger: 'blur',
      },
    ],
    wellNum: [
      {
        required: true,
        message: '请选择验收井号',
        trigger: 'change',
      },
    ],
    wellTeam: [
      {
        required: true,
        message: '请选择配合井队及所属单位',
        trigger: 'change',
      },
    ],
    preAcceptIndicator: [
      {
        required: true,
        message: '请输入预期验收指标',
        trigger: 'blur',
      },
    ],
    outUnitName: [
      {
        required: true,
        message: '请输入外协单位',
        trigger: 'blur',
      },
    ],
    outUnitLeaderName: [
      {
        required: true,
        message: '请输入外协负责人',
        trigger: 'blur',
      },
    ],
    conclusionWay: [
      {
        required: true,
        message: '请选择预计验收方式',
        trigger: 'change',
      },
    ],
    seftAccept: [
      {
        required: true,
        message: '请选择是否通过本单位亲自验收',
        trigger: 'change',
      },
    ],
    contractContent: [
      {
        required: true,
        message: '请输入合同主要服务内容',
        trigger: 'blur',
      },
    ],
  })

  const depts = ref([])

  //初始化数据
  const initFormData = (id, getType = 2) => {
    acceptApplyGet({
      id: id,
      getType,
    }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        if (getType == 1) {
          setFormData(res.data)
          initFormData(res.data.acceptApplyId, 2)
        } else {
          detailData.value = res.data || {}
          route.query.getType == 2 && setFormData(res.data.acceptApplyRespVO)
        }
      }
    })
  }

  const setFormData = (data) => {
    for (const key in ruleForm) {
      if (key == 'conclusionDate') {
        ruleForm[key] = data?.conclusionStart
          ? [
              $XEUtils.toDateString(
                data?.conclusionStart,
                'yyyy-MM-dd HH:mm:ss'
              ),
              $XEUtils.toDateString(data?.conclusionEnd, 'yyyy-MM-dd HH:mm:ss'),
            ]
          : []
      } else if (key == 'contractFulfill') {
        ruleForm[key] = data?.contractFulfillStart
          ? [
              $XEUtils.toDateString(
                data?.contractFulfillStart,
                'yyyy-MM-dd HH:mm:ss'
              ),
              $XEUtils.toDateString(
                data?.contractFulfillEnd,
                'yyyy-MM-dd HH:mm:ss'
              ),
            ]
          : []
      } else {
        ruleForm[key] = data[key] || ''
      }
    }
  }

  //表单提交
  const submitForm = async (formEl, type = 1) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        const params = {
          ...ruleForm,
          conclusionStart: ruleForm.conclusionDate[0],
          conclusionEnd: ruleForm.conclusionDate[1],
          contractFulfillStart: ruleForm.contractFulfill[0],
          contractFulfillEnd: ruleForm.contractFulfill[1],
          topicId: detailData.value.topicInfo?.id,
          id: detailData.value.acceptApplyRespVO?.id,
          wellTeamName:
            depts.value.find((item) => item.id == ruleForm.wellTeam)?.name ||
            '',
        }
        delete params.conclusionDate
        delete params.contractFulfill
        loading.value = true
        if (type == 2) {
          const api =
            route.query.id && route.query?.getType == 2
              ? acceptApplyUpdate
              : acceptApplyUpdate
          if (route.query?.getType == 1) {
            params.draftBoxId = route.query.id
          }
          api(params)
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                $baseMessage('修改成功')
                closeTabNavigate()
              }
            })
            .finally(() => {
              loading.value = false
            })
        } else {
          const formData = {
            id: route.query?.getType == 1 ? route.query.id : '',
            type: 'PROJECT_ACCEPT_RESULT',
            submitJson: JSON.stringify({
              ...params,
              acceptApplyId: detailData.value.acceptApplyRespVO.id,
              draftBoxId: route.query?.getType == 1 ? route.query.id : '',
            }),
          }

          postDraftBoxCreate(formData)
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                $baseMessage('保存草稿成功')
                closeTabNavigate()
              }
            })
            .finally(() => {
              loading.value = false
            })
        }
      }
    })
  }

  const getDepts = () => {
    getDeptPage().then((res) => {
      if (res.code == 0 || res.code == 200) {
        depts.value = res.data || []
      }
    })
  }

  getDepts()
  initFormData(route.query.id, route.query.getType)
</script>

<style lang="scss" scoped>
  .project-title {
    display: flex;
    align-items: center;
    width: 100%;
    min-height: 28px;
    padding: 10px;
    background: var(--vxe-table-header-background-color);

    .item {
      display: inline-flex;
      margin-right: 90px;
      font-size: $base-font-size-default;

      .label {
        color: $base-color-text-secondary;
      }
    }
  }

  .box {
    .common-title {
      display: flex;
      align-items: center;
      font-size: $base-font-size-default;
      font-weight: bold;
      color: $base-color-text-primary;

      .icon {
        margin-right: 10px;
      }
    }

    .sub-title {
      font-size: $base-font-size-small;
      font-weight: bold;
    }
  }
</style>
